package systems;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import entities.Question;

public class RecentlyUpdate {
	
	private static String cacheName = "recentlyUpdate";
	
	private static int limit = 50;
	
	public static void insert(Question question) {
		Cache cache=null;
    	try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e1) {
		   e1.printStackTrace();
		}
		
		List<Question> questions = new ArrayList<Question>();
		if(cache!=null&&cache.containsKey(cacheName))
		{
			questions = (List<Question>) cache.get(cacheName);
		}
		
		for (int i = 0; i < questions.size(); i++) {
			if (questions.get(i).getId().equals(question.getId())) {
				questions.remove(questions.get(i));
			}
		}
		
		if (questions.size() >= limit) {
			questions.remove(limit - 1);
		}
		
		questions.add(0, question);
		
		cache.put(cacheName, questions);
	}
	
	public static List<Question> getQuestions() {
		List<Question> questions = new ArrayList<Question>();
		
		Cache cache=null;
    	try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e1) {
		   //e1.printStackTrace();
		}
		
		if(cache!=null&&cache.containsKey(cacheName))
		{
			questions = (List<Question>) cache.get(cacheName);
		}
		
		return questions;
	}
}
